import {Component, OnInit} from "@angular/core";
import {Subject, BehaviorSubject, Observable} from "rxjs";

type ActionType = 'INCREASE' | 'DECREASE'
interface Action {
  type: ActionType
}
const INCREASE: ActionType = 'INCREASE'
const DECREASE: ActionType = 'DECREASE'

type State = number
type ChangeFn = (state: State) => State

@Component({
  selector: 'rx-redux',
  templateUrl: 'rx-redux.component.html'
})
export class RxReduxComponent implements OnInit {
  private action$$ = new Subject<Action>()
  private state$$ = new BehaviorSubject<State>(0)
  private ultimate_ = this.state$$.subscribe(console.log)

  private changeFn$: Observable<ChangeFn> = this.action$$.map((action) => {
    switch (action.type) {
      case INCREASE:
        return (state: State) => state + 1
      case DECREASE:
        return (state: State) => state - 1
      default:
        return (state: State) => state
    }
  })
  private state$ = this.changeFn$.scan((state, changeFn) => changeFn(state), 0)
  private intermediate_ = this.state$.subscribe(this.state$$)

  ngOnInit(): void {
  }

  increase() {
    this.action$$.next({type: INCREASE})
  }

  decrease() {
    this.action$$.next({type: DECREASE})
  }
}
